package _2观察者模式.Observable抽象类的使用;

import javax.swing.*;
import java.util.*;

public class ShowWord extends JPanel implements Observer {
    Observable subject; // 观察的主题
    JTextArea text;     // 文本区域
    TreeSet<String> wordList;   // 排序后的字符列表

    ShowWord(Observable subject) {
        this.subject = subject;
        subject.addObserver(this);
        text = new JTextArea(10, 15);
        text.setLineWrap(true);
        text.setWrapStyleWord(true);
        text.setEnabled(false);
        add(new JScrollPane(text));
        wordList = new TreeSet<>();
    }

    @Override
    public void update(Observable o, Object arg) {
        text.setText(null);
        text.append("出现的单词有（按字典排序）：\n");
        wordList.clear();
        String content = arg.toString();
        String regex = "[\\s\\d\\p{Punct}]+";
        String[] words = content.split(regex);
        wordList.addAll(Arrays.asList(words));
        for (String str : wordList) {
            text.append(str + " ");
        }
    }
}
